package com.eit.ntc.lmsbackend.struts.action;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;

public class LmsJAXBUtils {

    private static LmsJAXBUtils instance = null;
    private String jaxbContextName = "com.eit.ntc.lmsbackend.struts.jdo";

    private LmsJAXBUtils() {
    }

    public static LmsJAXBUtils getInstance() {
        if (instance == null) {
            instance = new LmsJAXBUtils();
        }
        return instance;
    }

    public void object2xml(Object obj, OutputStream output) throws Exception {
        try {
            JAXBContext jc = JAXBContext.newInstance(jaxbContextName);
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(obj, output);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        }
    }

    public Object xml2object(InputStream fileStream, String schemaFilename) throws Exception {
        File schemaFile = new File(schemaFilename);

        JAXBContext jc;
        Object obj = null;
        try {
            jc = JAXBContext.newInstance(jaxbContextName);
            Unmarshaller um = jc.createUnmarshaller();

            SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

            Schema schema = sf.newSchema(schemaFile);

            um.setSchema(schema);
            obj = um.unmarshal(fileStream);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        }
        return obj;

    }
}
